package com.sh.rbac.core.common.aspect;

import com.sh.rbac.domain.entity.JobLog;
import com.sh.rbac.core.common.enums.OperationStatusEnum;
import com.sh.rbac.service.JobLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 任务日志切面
 *
 * @author wb
 * @since 2024-07-01
 */

@Aspect
@Component
public class JobAspect {


    @Autowired
    private JobLogService jobLogService;


    /**
     * 切点
     */
    @Pointcut("execution(* org.springframework.scheduling.quartz.QuartzJobBean.executeInternal(..))")
    public void loginPointcut() {
    }

    /**
     * 后置通知
     *
     * @param joinPoint 连接点
     * @param result    返回结果
     */
    @AfterReturning(pointcut = "loginPointcut()", returning = "result")
    public void afterLogin(JoinPoint joinPoint, Object result) {
        recordLoginLog(joinPoint, "任务执行成功", OperationStatusEnum.SUCCESS.getCode());

    }

    /**
     * 异常通知
     *
     * @param joinPoint 连接点
     * @param e         异常
     */
    @AfterThrowing(pointcut = "loginPointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        recordLoginLog(joinPoint, e.getMessage(), OperationStatusEnum.FAILURE.getCode());
    }

    /**
     * 保存任务日志
     *
     * @param joinPoint 连接点
     * @param message 日志信息
     * @param status  执行状态
     */
    private void recordLoginLog(JoinPoint joinPoint, String message, Integer status) {
        JobExecutionContext context = (JobExecutionContext) joinPoint.getArgs()[0];
        JobKey jobKey = context.getJobDetail().getKey();

        JobLog jobLog = new JobLog();
        jobLog.setJobName(jobKey.getName());
        jobLog.setJobGroup(jobKey.getGroup());
        jobLog.setJobMessage(message);
        jobLog.setExecTime(new Date());
        jobLog.setStatus(status);
        jobLog.setCreateTime(new Date());

        jobLogService.save(jobLog);
    }
}
